//给你 root1 和 root2 这两棵二叉搜索树。请你返回一个列表，其中包含 两棵树 中的所有整数并按 升序 排序。. 
//
// 
//
// 示例 1： 
//
// 
//
// 
//输入：root1 = [2,1,4], root2 = [1,0,3]
//输出：[0,1,1,2,3,4]
// 
//
// 示例 2： 
//
// 
//
// 
//输入：root1 = [1,null,8], root2 = [8,1]
//输出：[1,1,8,8]
// 
//
// 
//
// 提示： 
//
// 
// 每棵树的节点数在 [0, 5000] 范围内 
// -105 <= Node.val <= 105 
// 
// Related Topics 树 深度优先搜索 二叉搜索树 二叉树 排序 
// 👍 141 👎 0

package com.cute.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.List;

public class AllElementsInTwoBinarySearchTrees {
    public static void main(String[] args) {
        new AllElementsInTwoBinarySearchTrees().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
    class Solution {
        /**
         *  想的复杂了，一开始准备在遍历的时候添加节点，还是单独遍历最后添加吧
         */
        public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
            List<Integer> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            List<Integer> res = new ArrayList<>();
            dfs(root1, list1);
            dfs(root2, list2);
            int index1 = 0, index2 = 0, l1 = list1.size(), l2 = list2.size();
            while (index1 < l1 || index2 < l2){
                int a = index1 < l1 ? list1.get(index1) : Integer.MAX_VALUE;
                int b = index2 < l2 ? list2.get(index2) : Integer.MAX_VALUE;
                if (a <= b) {
                    res.add(a);
                    index1++;
                }else {
                    res.add(b);
                    index2++;
                }
            }

            return res;
        }

        public void dfs(TreeNode node, List<Integer> list){
            if (node == null) return;
            dfs(node.left, list);
            list.add(node.val);
            dfs(node.right, list);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}